import { _decorator, Component, v3, Vec3, Vec2 } from 'cc';
import SelfPlayer from '../../Example/Script/SelfPlayer';
import PolygonNav2D from '../../PolygonNav/Script/PolygonNav2D';
import { Battle } from '../Battle';
import { TeammateAnimType, TeammateController } from './TeammateController';
import PolygonNavAgent from '../../PolygonNav/Script/PolygonNavAgent';
const { ccclass, property } = _decorator;

@ccclass('FormationFollowController')
export class FormationFollowController extends Component {

    @property(Number)
    followerIndex: number = 1;

    private isFollow: boolean = false;
    private controller: TeammateController;
    private maxDistance: number = 150;
    player: SelfPlayer

    onEnable() {
        this.controller = this.node.getComponent(TeammateController);
        this.player = this.node.getComponent(SelfPlayer);
        this.player.Init(Battle.PolygonNav2D.getComponent(PolygonNav2D), null, true);
    }

    BeginFollower() {
        this.isFollow = true;
    }

    UpdateFollowerIndex(index) {
        this.followerIndex = index;
    }

    update(deltaTime: number) {
        if (!Battle.playerNode || !this.isFollow)
            return;

        const result1 = new Vec3();
        let targetPosition = Battle.playerNode.position;
        let playerParentNode = Battle.playerNode.parent;
        Vec3.add(result1, targetPosition, playerParentNode.position);
        let targetNode = Battle.playerNode.getChildByName("followerNode" + this.followerIndex);
        const result2 = new Vec3();
        Vec3.add(result2, result1, targetNode.position);

        // let distance = Vec2.distance(this.node.getWorldPosition(), targetNode.getWorldPosition());
        // // if (distance >= this.maxDistance) 
        // {
        //     // 获取领导者方向
        //     // const leaderForward = Battle.playerNode.forward;
        //     if (this.node.position.x >= result2.x) {
        //         this.controller.bodyNode.setScale(-1, 1);
        //     }
        //     else {
        //         this.controller.bodyNode.setScale(1, 1);
        //     }
        //     const newPosition = v3();
        //     Vec3.lerp(newPosition, this.node.position, result2, 2 * deltaTime);
        //     this.node.setPosition(newPosition);
        //     if (distance > 50) {
        //         this.controller.PlayAnim(TeammateAnimType.Walk, 0);
        //     }
        //     else {
        //         this.controller.PlayAnim(TeammateAnimType.Idle, 0);
        //     }
        // }
        // else{
        //     this.controller.anmController.SetNone();
        // }
        if (this.player.IsMove) {
            this.controller.PlayAnim(TeammateAnimType.Walk, 0);
        }
        else{
            this.controller.PlayAnim(TeammateAnimType.Idle, 0);
        }
        this.player.SetTargetPos(new Vec2(result2.x, result2.y));
    }
}


